﻿// 
// $Id: ZenManager.cs 3981 2010-11-02 11:12:16Z unknown $
// 
// Zen UI Toolkit Copyright (c) 2010, Paul Clancy.  All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification, are permitted provided 
// that the following conditions are met:
// 
// * 	Redistributions of source code must retain the above copyright notice, this list of 
// 	conditions and the following disclaimer.
// 
// * 	Redistributions in binary form must reproduce the above copyright notice, this list of 
// 	conditions and the following disclaimer in the documentation and/or other materials 
// 	provided with the distribution.
// 
// * 	Neither the name of AppTek nor the names of its contributors may be used to endorse 
// 	or promote products derived from this software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
// THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// 

#region

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.UI;

#endregion

namespace Zen.Toolkit
{
    [ToolboxData("<{0}:ZenManager runat=\"server\" />")]
    [Description("A Manager is required on every page")]
    [DojoRequires(ModuleName = "dijit.Dialog")]
    [ToolboxBitmap(typeof (ZenManager), "Resources.Icons.Toolbox.weather_sun.bmp")]
    public class ZenManager : WidgetBase
    {
        public const string ZEN_MANAGER_CONTEXT_KEY = "$ZenManager$";
        private readonly ScriptManager _scriptManager = new ScriptManager();

        public ZenManager() : base(HtmlTextWriterTag.Div)
        {
        }

        public ScriptManager Script
        {
            get { return _scriptManager; }
        }

        [DefaultValue("false")]
        public bool ParseOnLoad { get; set; }

        [DefaultValue("false")]
        public bool IsDebug { get; set; }

        [DojoProperty(Name = "theme")]
        public Enums.DojoTheme Theme
        {
            get
            {
                object o = ViewState["Theme"];
                return (o == null) ? Enums.DojoTheme.Claro : (Enums.DojoTheme) o;
            }

            set { ViewState["Theme"] = value; }
        }


        protected override void OnInit(EventArgs e)
        {
            Page.EnableViewState = false;

            base.OnInit(e);
            HttpContext.Current.Items[ZEN_MANAGER_CONTEXT_KEY] = this;


            Script.AddStyleResource(Page, "Zen.Toolkit.Resources.Style.zen-base.css");
            Script.AddStyleReference(ScriptManager.Format(ScriptTemplate.DojoThemeStyleLink, Theme));
            Script.AddIncludeReference(ScriptTemplate.DojoLibraryUrl);
            Script.AddIncludeResource(Page, "Zen.Toolkit.Resources.Script.zen-manager.js");

            //this.Script.AddFragment("zentheme", Placement.OnLoad, ScriptTemplate.DojoThemeBodyClass, this.Theme);
            Script.AddFragment(0, "zenajax", Placement.OnBeforeInit,
                               string.Format("$zen = new zen.zenManager('{0}');", Theme.ToString().ToLowerInvariant()));
            Script.AddOnLoadScript("zenconfig", GetConfigScript());
            //this.Script.AddFragment("zenmask", Placement.OnAfterInit, "$zen.hideMask();");
            Page.PreRenderComplete += PagePreRenderComplete;
        }

        private void PagePreRenderComplete(object sender, EventArgs e)
        {
            Page.Header.Controls.Add(_scriptManager);
        }

        protected string GetConfigInit()
        {
            var configItems = new List<string> {"isZen: true"};

            if (ParseOnLoad)
            {
                configItems.Add(string.Format("parseOnLoad: {0}", JsonUtils.Serialize(ParseOnLoad)));
            }
            if (IsDebug)
            {
                configItems.Add(string.Format("isDebug: {0}", JsonUtils.Serialize(IsDebug)));
            }
            return string.Join(", ", configItems);
        }

        protected string GetConfigScript()
        {
            var sb = new StringBuilder();

            sb.Append("\nvar djConfig = {");
            sb.Append(GetConfigInit());
            sb.Append(" };\n");


            return sb.ToString();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("<div id=\"zenCallbackDialog\"></div>");
            writer.Write("<div id=\"zenCallbackContent\"></div>");

            writer.Write("<div id=\"zenMaskPage\"></div>");
            writer.Write("<div id=\"zenMaskDialog\" class=\"dijitDialog\" tabindex=\"-1\" title=\"\">");
            writer.Write("<div class=\"zenMaskImage\"></div>");
            writer.Write("<div class=\"zenMaskText\">Loading...</div>");
            writer.Write("</div>");
            base.Render(writer);
        }

        public static ZenManager GetInstance(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            return context.Items[ZEN_MANAGER_CONTEXT_KEY] as ZenManager;
        }
    }
}